package com.online.web.shiro.biz.shiro;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.stereotype.Component;

/**
 * URL拦截器
 * 
 * @author tongyufu
 *
 */
@Component
public class UrlAuthorizationFilter extends AuthorizationFilter {

    Logger log = LogManager.getLogger(UrlAuthorizationFilter.class);

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response,
                                      Object mappedValue) throws Exception {
        String url = WebUtils.toHttp(request).getRequestURI();
        Subject subject = SecurityUtils.getSubject();

        if (StringUtils.isBlank(url)) {
            log.error("拦截到URL为空");
            return false;
        }
        if ("/".equals(url)) {
            return subject.getPrincipal() == null ? false : true;
        }
        if (url.equals("/iframeMenu") && subject.isPermitted(request.getParameter("url"))) {
            return true;
        }
        if (subject.isPermitted(url)) {
            return true;
        }
        return false;
    }

}
